package com.hongshan.wallet.core.home

import android.app.Application
import android.content.Intent
import android.databinding.ObservableField
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.base.SingleLiveEvent
import com.hongshan.wallet.bean.PaymentMethod
import com.hongshan.wallet.copyStr
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.log
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.router.go
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.util.AutoInject
import com.hongshan.wallet.util.NetworkFileUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.io.File


/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.home
 * @author   : zhangxx
 * @date     : 2019/4/10
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */
class TopUpViewModel(application: Application) :MyViewModel(application) {

    @AutoInject(Constant.ROUTE_PARAMS_KEY.TOP_UP_PAY_METHOD)
    var payMethod: PaymentMethod? = null

    val name = ObservableField<String>()
    val account = ObservableField<String>()
    val bank = ObservableField<String>()
    val qrUrl = ObservableField<String>()
    val screenPic = ObservableField<String>()
    val code = ObservableField<String>()

    val selectPic = SingleLiveEvent<Unit>()

    val showBankPay = ObservableField(true)
    val showWxOrAliPay = ObservableField(true)

    val copyName = View.OnClickListener {
        copyStr(payMethod?.accoun_name)
    }
    val copyAccount = View.OnClickListener {
        copyStr(payMethod?.card_no)
    }
    val copyBank = View.OnClickListener {
        copyStr(payMethod?.name)
    }

    val saveQRCode = View.OnClickListener {
        Glide.with(application).asBitmap().addListener(object : RequestListener<Bitmap> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<Bitmap>?,
                isFirstResource: Boolean
            ): Boolean {
                e?.printStackTrace()
                log(payMethod?.qrcode_url)
                toast("保存失败")
                return true
            }

            override fun onResourceReady(
                resource: Bitmap?,
                model: Any?,
                target: Target<Bitmap>?,
                dataSource: DataSource?,
                isFirstResource: Boolean
            ): Boolean {
                MediaStore.Images.Media.insertImage(
                    MyApplication.applicationContext.contentResolver,
                    resource,
                    "qrCode",
                    "pay qrcode"
                )
                MyApplication.applicationContext.sendBroadcast(
                    Intent(
                        Intent.ACTION_MEDIA_MOUNTED,
                        Uri.parse("file://" + Environment.getExternalStorageDirectory())
                    )
                )
                toast("保存成功")
                return true
            }

        }).load(payMethod?.qrcode_url).preload()
    }

    val selectImg = View.OnClickListener {
        selectPic.call()
    }

    val commit = View.OnClickListener {
        val path = screenPic.get()
        if (path != null && path.isNotEmpty()) {
            val file = File(path)
            if (file.exists()){
                showLoading.call()
                NetworkFileUtils.upload("/api/v1/uploadImg",file.absolutePath){
                    if (it!=null){
                        GlobalScope.launch(Dispatchers.Main) {
                            val result = GlobalScope.async(Dispatchers.IO) {
                                tryRun { HttpClient.httpApi.commitTopUp(payMethod!!.code, it).execute() }
                            }
                            val body = result.await()?.body()
                            showSuccess.call()
                            if (body?.code == 0){
                                go(RouterIndex.TOP_UP_RESULT)
                            }
                        }
                    } else{
                        showSuccess.call()
                    }
                }
            }
        } else{
            toast("请选择上传成功截图")
        }
    }

    override fun initial() {
        if (payMethod != null) {
            name.set("收款姓名:  " + payMethod?.accoun_name)
            when (payMethod?.code) {
                PaymentMethod.CODE_WECHAT -> {
                    showWxOrAliPay.set(true)
                    showBankPay.set(false)
                    qrUrl.set(payMethod?.qrcode_url)
                }
                PaymentMethod.CODE_ALIPAY -> {
                    showWxOrAliPay.set(true)
                    showBankPay.set(false)
                    qrUrl.set(payMethod?.qrcode_url)
                }
                else -> {
                    showWxOrAliPay.set(false)
                    showBankPay.set(true)
                    account.set("收款账户:  " + payMethod?.card_no)
                    bank.set("收款银行:  " + payMethod?.name)
                }
            }
        }
    }
}